package com.itsoku.chat34;

import java.util.Random;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DelayTest {
    private static DelayQueue<TaskInfo> queue = new DelayQueue<>();//延迟队列
    private static ExecutorService es =  Executors.newFixedThreadPool(3);//3个线程的线程池
    public static void main(String[] args){  
        while (true) {  
            try {
                if (queue.size() <= 0) {
                    //获取任务放入队列
                    getTask();
                    if (queue.size() <= 0) {
                        System.out.println("没有任务睡眠10秒");
                        //没有任务睡眠10秒  
                        Thread.sleep(10 * 1000);
                    }
                } else {
                    TaskInfo task = queue.take();
                    es.submit(() -> {
                        System.out.println("执行任务：" + task.getId() + ":" + task.getData());
                    });
                }  
            }catch (Exception e){  
                e.printStackTrace();  
            }  
        }  
    }  
    //模拟从数据库获取 将来10秒中内即将执行的任务  
    public static void getTask(){  
        Random r = new Random();
        int t = r.nextInt(2);  
        if(t==0){  
            return;  
        }  
        TaskInfo t1 = new TaskInfo(1,1,"任务1",1000);  
        TaskInfo t2 = new TaskInfo(2,2,"任务2",2000);  
        TaskInfo t3 = new TaskInfo(3,3,"任务3",3000);  
        TaskInfo t4 = new TaskInfo(4,4,"任务4",4000);  
        TaskInfo t5 = new TaskInfo(5,5,"任务5",5000);  
        TaskInfo t6 = new TaskInfo(6,6,"任务6",6000);  
        TaskInfo t7 = new TaskInfo(7,7,"任务7",7000);  
        TaskInfo t8 = new TaskInfo(8,8,"任务8",8000);  
        queue.offer(t1);  
        queue.offer(t2);  
        queue.offer(t3);  
        queue.offer(t4);  
        queue.offer(t5);  
        queue.offer(t6);  
        queue.offer(t7);  
        queue.offer(t8);  
    }  
}